//
//  WBUserAccount.swift
//  Swift_sina
//
//  Created by TFB_WGP on 2017/9/11.
//  Copyright © 2017年 TFB_WGP. All rights reserved.
//

import UIKit

class WBUserAccount: NSObject {
    
    var access_token: String?
    var uid: String?
    var expires_in: TimeInterval = 0{
        //监听set方法
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate: Date?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    
    override init() {
        super.init()
        //从次加载保存的文件
        guard let data = try? NSData(contentsOfFile: userAccountJsonPath) as Data else {
            return
        }
        
        let dict = try?
        JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
        //把字典赋给属性值
        yy_modelSet(with: dict ?? [:])
        
        //判断token是否过期,测试过期日期
//        expiresDate = Date(timeIntervalSinceNow: -3600*24)
        if expiresDate?.compare(Date()) != ComparisonResult.orderedDescending {
            //账户过期
            access_token = nil
            uid = nil
            
            //删除账户文件
            try? FileManager.default.removeItem(atPath: userAccountJsonPath)
            
            //        发送登录通知
            NotificationCenter.default.post(name: NSNotification.Name(WBUserShouldLoginNotifiction), object: nil)
        }
        
        //账户正常
    }
    
    /// 存储账户模型的方法
    func saveAccount() -> Void {
        //模型转字典
        var dict = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        //删除expires_in
        dict.removeValue(forKey: "expires_in")
        //字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
            return
        }
        //写入磁盘
        let filepath = userAccountJsonPath
        (data as NSData).write(toFile: filepath, atomically: true)
    }
    
    override var description: String{
        return yy_modelDescription();
    }
}
